const mongoose = require("mongoose");

// 等待值的接收
const get = async ({ curPage, eachPage }) => {
    // 通过位运算符将类型转换为Number类型
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
    }
    // model传一个参数时表示获取这个model对象
    const ordersModel = mongoose.model("orders");
    // 获取当前model映射的那个集合里面存放的文档总数
    data.total = await ordersModel.countDocuments();
    // Math.ceil 向上取整
    data.maxPage = Math.ceil(data.total / eachPage);
    // 计算跳过的条数
    const skipNum = (curPage - 1) * eachPage;
    // find是异步方法，populate(填充(找到相对应的完整数据返回))  skip(跳过多少条). limit(限制范围).exec=execute(执行)  sort({排序条件})
    data.rows = await ordersModel.find().populate("userId").populate("commoditiesId").skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();
    // 返回数据给路由commoditiesId
    return data;
}

// 新增订单
const addOrders = async ({ userId, commoditiesId, time,  state, price,orderInfo,count}) => {
    // model传一个参数时表示获取这个model对象
    const ordersModel = mongoose.model("orders");
    // 添加订单数据
    return await ordersModel.create({ userId, commoditiesId, time,  state, price,orderInfo,count});
}

const findOne = async _id => {
    // model传一个参数时表示获取这个model对象
    const ordersModel = mongoose.model("orders");
    return await ordersModel.findOne({ _id });
}



// 删除订单
const removeOrders = async ({ _id }) => {
    const ordersModel = mongoose.model("orders");
    // remove删除数据库_id匹配的数据
    await ordersModel.deleteOne({ _id });
}

//根据订单状态查询订单
const findOrdersToState = async ({_id,state}) => {
    // model传一个参数时表示获取这个model对象
    const ordersModel = mongoose.model("orders");
    const userOrders =  await ordersModel.find({ userId:_id });
    let complete=[];
    if (state=="全部") {
        return userOrders;
    }else{
        for (let i = 0; i < userOrders.length; i++) {
            if (state==userOrders[i].state) {
                complete.push(userOrders[i])
            }
            
        }
        return complete;
    }
}

// 暴露接口
module.exports = {
    get,
    addOrders,
    removeOrders,
    findOne,
    findOrdersToState
}
